package com.arcsoft.crud.base;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.arcsoft.crud.Constants.Global;
import com.arcsoft.crud.util.ConnectionDB;
import com.arcsoft.log.entity.OptimizeAnalyzeLog;
import com.google.common.util.concurrent.RateLimiter;

public abstract class TaskBase implements Runnable{
	
	protected Date startTime;

	protected RateLimiter rateLimiter;
	protected int printInfoInterval; //单位为秒.
	protected long previous = 0L;
	  
	protected String taskLogTable;
	protected int threadIndex;
	Map<String, Long> map = new HashMap<String, Long>();
	
	protected TaskBase (int printInfoInterval, String taskLogTable, int threadIndex){
		
		this.printInfoInterval = printInfoInterval;
		this.taskLogTable = taskLogTable;
		this.rateLimiter = RateLimiter.create(1d / printInfoInterval);//可以动态监测该任务在一秒内允许执行多少次，在这里1/10 即 每秒钟执行0.1次，即10秒钟执行一次
	    this.threadIndex = threadIndex;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		
	}
	
	public void insertLog(OptimizeAnalyzeLog optimizeAnalyzeLog){
		ConnectionDB db = new ConnectionDB();
        
        String sql = "insert into "+taskLogTable+"(sceneDesc,type,startTime,endTime,extendTime,requestDetail) values(?,?,?,?,?,?)";
         
        Object arrays[] = {optimizeAnalyzeLog.getSceneDesc(),
        		           optimizeAnalyzeLog.getType(),
			        	   optimizeAnalyzeLog.getStartTime(),
			        	   optimizeAnalyzeLog.getEndTime(),
			        	   optimizeAnalyzeLog.getExtendTime(),
			        	   optimizeAnalyzeLog.getRequestDetail()
			        	  };
         
        @SuppressWarnings("unused")
		int line = db.updateBySql(sql, arrays);
	}
	
	@SuppressWarnings("static-access")
	public String parseSql(String sql, Object arrays[]){
		for(Object obj : arrays){
			sql = this.replaceString(sql, obj.toString(), 1);
		}
		return sql;
	}
	
	 public static String replaceString(String str, String rstr, int a) {
	        String searchStr = "?";
	        int index = str.indexOf(searchStr);
	        int count = 1;
	        while (count != a) {
	            index = str.indexOf(searchStr, index + 1);
	            count++;
	        }
	 
	        return str.substring(0, index) + rstr + str.substring(index + 1);
	    }
	
	public void logInfo(Date startTime, Date endTime, String requestDetail, int extendTime){
		
	}
	
	public Map<String, Long> prepareData(){
		
		if(!map.isEmpty())
			return map;
	
		ConnectionDB db = new ConnectionDB();
		String sql = "select count(1) as count, min(id) as startId, max(id) as endId from people";
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> mapList = db.getDataBySql(sql, null);
		if(mapList != null && mapList.size()!=0)
		{
			Long obj = (Long)mapList.get(0).get("count");
			Long scope = obj.longValue()/Global.THREAD_COUNT;
			Long startId = threadIndex*scope+(Integer)mapList.get(0).get("startId");
			Long endId = startId+(threadIndex+1)*scope;
			if(endId >(Integer)mapList.get(0).get("endId"))
				endId = ((Integer)mapList.get(0).get("endId")).longValue();
			map.put("scope", scope);
			map.put("startId", startId);
			map.put("endId", endId);
		}
		
		return map;
	}
	
	/**
	   * 产生随机字符串
	   * */
	private static Random randGen = null;
	private static char[] numbersAndLetters = null;

	public static final String randomString(int length) {
	         if (length < 1) {
	             length = 4;
	         }
	         if (randGen == null) {
	                randGen = new Random();
	                numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" +
	                   "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();
	                 }
	         char [] randBuffer = new char[length];
	         for (int i=0; i<randBuffer.length; i++) {
	             randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
	         }
	         return new String(randBuffer);
	}

	/**
	 * 间隔printInfoInterval的时间打印日志信息
	 */
	protected void printInfo(long current, Date startTime) {
		if (rateLimiter.tryAcquire()) {
			long totalTime = (new Date().getTime() - startTime.getTime()) / 1000;
			long requests = (current - previous) + 1;
	
			long tps = requests / Global.PRINT_INTERVAL_SECONDS;
			
			String printTime = (new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss")).format(new Date());
			
			System.out.printf("current_time:"+printTime+
					",Thread %02d finish %,d requests after %d seconds. Last TPS is %,d.\n",
					threadIndex, current, totalTime, tps);
			previous = current;
		}
	}
}
